import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';

import '../constant/channel_constant.dart';
import '../utils/log_utils.dart';

//
//事件管理器
//
/// 一体机扫描
const String eventScanAIO = 'eventScanAIO';

/// 一体机停止扫描
const String eventStopScanAIO = 'eventStopScanAIO';

/// 一体机连接
const String eventConnectAIO = 'eventConnectAIO';

/// 一体机断连
const String eventDisConnectAIO = 'eventDisConnectAIO';

/// 一体机连接状态
const String eventConnectStatus = 'eventConnectStatus';

/// 配对信息编码
const String eventEndianUser = 'eventEndianUser';

/// 蓝牙数据
const String eventBluetooth = 'eventBluetooth';

/// wifi 名
const String getEventWifi = 'eventWifi';

/// wifi 名编码
const String eventEndianWifi = 'eventEndianWifi';

/// Android app 升级请求
const String eventAppUpgrade = 'eventAppUpgrade';

/// 下载进度
const String eventDownloading = 'eventDownloading';

/// 跳转到 app 推送设置管理
const String eventJumpAppManagerPush = 'eventJumpAppManagerPush';
const String eventOpenPushNoti = 'eventOpenPushNoti';
const String eventClosePushNoti = 'eventClosePushNoti';
const String eventOpenPermission = 'eventOpenPermission';

const String eventBleCentralState = 'eventBleCentralState';

///抽象接口
mixin EventManagerInterface {
  void notify(String methodName, Map<dynamic, dynamic> data) {}
}

///事件管理器
class EventManager {
  static EventManager? _instance;

  // 私有的命名构造函数
  EventManager._internal();

  static EventManager getIns() {
    if (_instance == null) {
      _instance = EventManager._internal();
      _instance!.startListener();
    }

    return _instance!;
  }

  List<EventManagerInterface> observers = [];

  bool isStarted = false;

  void addObserver(EventManagerInterface observer) {
    observers.add(observer);
  }

  void removeObserver(EventManagerInterface observer) {
    observers.remove(observer);
  }

  void startListener() {
    if (isStarted) {
      return;
    }

    isStarted = true;

    scanAIOMethodChannel.setMethodCallHandler((MethodCall methodCall) async {
      if (methodCall.method == eventBleCentralState) {
        LogUtils.log('flutter 接收到 ${methodCall.method} 方法');
        LogUtils.log('flutter 接收到 ${methodCall.arguments}');
      }
      String methodName = methodCall.method;
      Map<dynamic, dynamic>? data = methodCall.arguments;
      for (int i = 0; i < observers.length; i++) {
        EventManagerInterface observer = observers[i];
        observer.notify(methodName, data ?? {});
      }
    });

    // androidLoginByAliCode.setMethodCallHandler((MethodCall methodCall) async {
    //   LogUtils.log('flutter 接收到 ${methodCall.method} 方法');
    //   LogUtils.log('flutter 接收到 ${methodCall.arguments}');
    //   String methodName = methodCall.method;
    //   Map<dynamic, dynamic>? data = methodCall.arguments;
    //   for (int i = 0; i < observers.length; i++) {
    //     EventManagerInterface observer = observers[i];
    //     observer.notify(methodName, data ?? {});
    //   }
    // });
  }
}
